import { getDetail } from '../../service/goods'

Page({
  data: {
    detailObj: {},
    swiperImgList: [],
    isCollect: false
  },
  GoodsInfo: {},
  onShow() {
    let currentPages =  getCurrentPages();
    let goods_id = currentPages[currentPages.length -1].options.goods_id;

    this.pageInit(goods_id);
  },
  pageInit: async function (goods_id) {
    let detail = await getDetail(goods_id);
    let collect = wx.getStorageSync('collect') || [];

    this.GoodsInfo = detail.data.message;
    let { pics, goods_price, goods_name, goods_introduce, pics_mid } = detail.data.message;
    let swiperImgList = pics.map(item => item.pics_big);
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id);
    // 由于数据太多，所以只存储需要的
    // 由于部分手机不支持.webp格式，所以暂时转化为jpg格式（最好和后端沟通一下）
    this.setData({
      detailObj: {
        pics,
        goods_name,
        goods_price,
        goods_introduce: goods_introduce.replace(/\.webp/g, '.jpg'),
        pics_mid
      },
      swiperImgList,
      isCollect
    })
  },
  // 实现点击放大预览图片功能
  handlePreviewImage(e) {
    let imgUrl = e.currentTarget.dataset.imgurl;
    wx.previewImage({
      current: imgUrl,
      urls: this.data.swiperImgList
    });
  },
  // 实现加入购物车的功能
  handleAddCart() {
    let carts = wx.getStorageSync('carts') || [];
    this.GoodsInfo.is_select = true;
    let index = carts.findIndex(item => item.goods_id === this.GoodsInfo.goods_id);
    if (index === -1) {
      this.GoodsInfo.num = 1;
      carts.push(this.GoodsInfo);
    } else {
      carts[index].num += 1;
    }
    wx.setStorageSync('carts', carts);
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      mask: true
    });
  },
  handleCollect() {
    let collect = wx.getStorageSync('collect') || [];
    let isCollect = true;
    let index = collect.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);

    if(index === -1) {
      collect.push(this.GoodsInfo);
    }else {
      collect.splice(index, 1);
      isCollect = false;
    }
    this.setData({
      isCollect
    });
    wx.setStorageSync('collect', collect);
  }
})